package com.zdj.email.service.impl;

import com.zdj.email.entity.*;
import com.zdj.email.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.ITemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.ArrayDeque;
import java.util.Date;
import java.util.Queue;

/**
 * 简单文本的邮件
 *
 * @Author: wangxl
 * @Date: 2019/3/27 16:28
 */
@Component
@Slf4j
public class MailServiceImpl implements MailService {

    Queue<MimeMessage> mimeMessages = new ArrayDeque<>();
    Queue<SimpleMailMessage> simpleMailMessages = new ArrayDeque<>();
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private ITemplateEngine templateEngine;

    @Value("${spring.mail.fromMailaddr}")
    private String from;

    /**
     * 添加一封简单的邮件
     *
     * @param entity
     */
    @Override
    public void addSimpleMail(SimpleEntity entity) {
        if (entity == null || entity.getToPerson() == null)
            return;
        int len = entity.getToPerson().size();
        if (len <= 0)
            return;
        try {
            simpleMailMessages.clear();
            for (int i = 0; i < len; i++) {
                SimpleMailMessage message = new SimpleMailMessage();
                message.setFrom(from);
                message.setTo(entity.getToPerson().get(i));
                message.setSubject(entity.getSubject());
                message.setText(entity.getContent());
                message.setSentDate(new Date());
                if (StringUtils.isNotBlank(entity.getBcc()))
                    message.setBcc(entity.getBcc());
                if (StringUtils.isNotBlank(entity.getCc()))
                    message.setCc(entity.getCc());
                simpleMailMessages.add(message);
                log.info("第-" + i + "-个简单邮件已进入队列等待发送！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 添加一封html邮件
     * @param entity
     */
    @Override
    public void addHtmlMail(HtmlEntity entity) {
        if (entity == null || entity.getToPerson() == null)
            return;
        int len = entity.getToPerson().size();
        if (len <= 0)
            return;
        try {
            for (int i = 0; i < len; i++) {
                MimeMessage message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(from);
                helper.setTo(entity.getToPerson().get(i));
                helper.setSubject(entity.getSubject());
                helper.setText(entity.getContent(), true);
                if (StringUtils.isNotBlank(entity.getBcc()))
                    helper.setBcc(entity.getBcc());
                if (StringUtils.isNotBlank(entity.getCc()))
                    helper.setCc(entity.getCc());
                mimeMessages.add(message);
                log.info("第-" + i + "-个HTML邮件已进入队列等待发送！");
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加一封带附件邮件
     * @param entity
     */
    @Override
    public void addAttachemntMail(AttachEntity entity) {
        if (entity == null || entity.getToPerson() == null)
            return;
        int len = entity.getToPerson().size();
        if (len <= 0)
            return;
        try {
            for (int i = 0; i < len; i++) {
                MimeMessage message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(from);
                helper.setTo(entity.getToPerson().get(i));
                helper.setSubject(entity.getSubject());
                helper.setText(entity.getContent(), true);
                if (StringUtils.isNotBlank(entity.getBcc()))
                    helper.setBcc(entity.getBcc());
                if (StringUtils.isNotBlank(entity.getCc()))
                    helper.setCc(entity.getCc());
                for (String val : entity.getFiles()) {
                    helper.addAttachment(val.substring(val.lastIndexOf(File.separator) + 1),
                            new FileSystemResource(val));
                }
                mimeMessages.add(message);
                log.info("第-" + i + "-个带附件邮件已进入队列等待发送！");
            }
        } catch (MessagingException e) {
            e.printStackTrace();
            log.info("发送带附件邮件失败！");
        }
    }

    /**
     * 添加一封内嵌静态资源的邮件
     * @param entity
     */
    @Override
    public void addInlineResourceMail(InlineResourceEntity entity) {
        if (entity == null || entity.getToPerson() == null)
            return;
        int len = entity.getToPerson().size();
        if (len <= 0)
            return;
        try {
            for (int i = 0; i < len; i++) {
                MimeMessage message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(from);
                helper.setTo(entity.getToPerson().get(i));
                helper.setSubject(entity.getSubject());
                helper.setText(entity.getContent(), true);
                for (String key : entity.getRscMap().keySet()) {
                    helper.addInline(key, new FileSystemResource(
                            new File(entity.getRscMap().get(key))));
                }
                mimeMessages.add(message);
                log.info("第-" + i + "-个嵌入静态资源的邮件已进入队列等待发送！");
            }
        } catch (MessagingException e) {
            log.error("发送嵌入静态资源的邮件时发生异常！", e);
        }
    }

    /**
     * 添加一封带html模板的邮件
     * @param entity
     */
    @Override
    public void addTemplateMail(TemplateEntity entity) {
        if (entity == null || entity.getToPerson() == null)
            return;
        int len = entity.getToPerson().size();
        if (len <= 0)
            return;
        Context context = new Context();
        //设置模板参数
        for(String key:entity.getParams().keySet())
        {
            context.setVariable(key,entity.getParams().get(key));
        }
        String emailContent = templateEngine.process("emailTemplate", context);
        HtmlEntity htmlEntity=new HtmlEntity(entity);
        htmlEntity.setContent(emailContent);
        addHtmlMail(htmlEntity);
    }

    /**
     * 简单邮件发送
     */
    @Override
    public void sendSimple() {
        int i=1;
        while (!simpleMailMessages.isEmpty()) {
            SimpleMailMessage message = simpleMailMessages.poll();
            mailSender.send(message);
            log.info("第-" + i + "-个简单邮件已发送--还有-"+simpleMailMessages.size()+"-个等待发送！");
            i++;
        }
    }

    /**
     * 其他邮件发送
     */
    @Override
    public void sendOthers() {
        int i=1;
        while (!mimeMessages.isEmpty()) {
            MimeMessage message = mimeMessages.poll();
            mailSender.send(message);
            log.info("第-" + i + "-个复合邮件已发送--还有-"+mimeMessages.size()+"-个等待发送！");
            i++;
        }
    }
}
